package com.kyang.musiconline.dao;

import cn.hutool.core.util.IdUtil;
import com.kyang.musiconline.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * @author kyang
 */
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public boolean insert(User user) {
        String id = IdUtil.getSnowflake(1L, 1L).nextIdStr();
        Date now = new Date();
        user.setCreateDate(now);
        user.setUpdateDate(now);
        user.setId(id);
        String sql = "insert into user values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        int count = jdbcTemplate.update(sql, user.convertObjects());
        return count == 1;
    }

    public List<User> getAllUser(String userName, String address) {
        String conditions = "1 = 1";
        if (userName != null) {
            conditions += " and user_name = '" + userName + "'";
        }
        if (address != null) {
            conditions += " and address = '" + address + "'";
        }
        String sql = "select * from user where " + conditions + " order by id desc";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }


    public boolean changePassword(String userId, String password) {
        String sql = "update user set password=?, update_date=? where id=? and is_delete=0";
        Object[] objects = new Object[3];
        objects[0] = password;
        objects[1] = new Date();
        objects[2] = userId;
        int count = jdbcTemplate.update(sql, objects);
        return count == 1;
    }

    public boolean changeUserInfo(User user) {
        String sql = "update user set nick_name=?,sex=?,age=?,phone=?,address=? where id=? and is_delete=0";
        Object[] objects = new Object[6];
        objects[0] = user.getNickName();
        objects[1] = user.getSex();
        objects[2] = user.getAge();
        objects[3] = user.getPhone();
        objects[4] = user.getAddress();
        objects[5] = user.getId();
        int count = jdbcTemplate.update(sql, objects);
        return count == 1;
    }

    public User getUserById(String userId) {
        String sql = "select * from user where id=? and is_delete=0";
        Object[] objects = new Object[1];
        objects[0] = userId;
        return jdbcTemplate.queryForObject(sql, new User(), objects);
    }

    public User getUserByAccount(String account) {
        String sql = "select * from user where account=? and is_delete=0";
        Object[] objects = new Object[1];
        objects[0] = account;
        return jdbcTemplate.queryForObject(sql, new User(), objects);
    }
}
